package cn.com.backstage.controller;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiT_member_wemedia;
import cn.com.api.entity.ApiT_user_admin;
import cn.com.api.entity.U_article;
import cn.com.api.entity.U_article_cate;
import cn.com.api.entity.U_article_resource;
import cn.com.api.entity.U_cate;
import cn.com.api.entity.U_label;
import cn.com.api.entity.Ylj_All_Label_Obj;
import cn.com.api.entity.Ylj_Article_Label_Obj;
import cn.com.api.service.ApiT_member_wemediaService;
import cn.com.api.service.StartOnLoadService;
import cn.com.api.service.U_articleService;
import cn.com.api.service.U_article_cateService;
import cn.com.api.service.U_article_resourceService;
import cn.com.api.service.U_cateService;
import cn.com.api.service.U_labelService;
import cn.com.backstage.controller.base.U_articleBaseController;
import cn.com.util.BaseObj;
import cn.com.util.DateUtil;
import cn.com.util.HourGap;
import cn.com.util.ImageUtils;
import cn.com.util.JsonUtil;
import cn.com.util.ReturnListObject;
import cn.com.util.ReturnSingleObject;
import cn.com.util.Util;
import cn.com.util.Utils;

@Controller
@RequestMapping(Utils.SYS_BACKSTAGE)
public class U_articleBackController extends U_articleBaseController {

	private static Logger logger = Logger.getLogger(U_articleBackController.class);

	@Autowired
	private U_cateService u_cateService;
	@Autowired
	private U_cateService U_cateService;
	@Autowired
	private U_articleService u_articleService;
	@Autowired
	private U_labelService u_labelService;
	@Autowired
	private ApiT_member_wemediaService apiT_member_wemediaService;
	@Autowired
	private U_article_cateService u_article_cateService;
	@Autowired
	private U_article_resourceService u_article_resourceService;
	@Autowired
	private StartOnLoadService startOnLoadService;

	/**
	 * 列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "article-list4")
	public ModelAndView article_list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String title = request.getParameter("title");

		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_list4edit.jsp");
		if (request.getParameter("is_answer") != null) {
			List<U_article> u_articles = u_articleService.findU_articles();
			mv.addObject("u_articles", u_articles);
		} else {
			List<Map<String, Object>> u_articles = u_articleService.findArticleLikeTitle(title);
			mv.addObject("u_articles", u_articles);
		}

		return mv;
	}

	/**
	 * 批量删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "article-delete-batch")
	public void article_delete_batch(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("article_ids");
		String[] id_list = ids.substring(1).split(",");

		int ret_i = 0;
		for (String id : id_list) {
			// delete
			ret_i = u_articleService.deleteU_article(Integer.valueOf(id));
		}
		//
		if (ret_i > 0) {
			map.put(Util.RESULT, Util.RESULT_RC_SUCCESS);
			map.put(Util.MESSAGE, "删除成功！");
		}

		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 编辑帮助文档
	 **/
	@RequestMapping({ "document-show" })
	public ModelAndView document_show(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = null;
		String article_id = request.getParameter("article_id");
		try {
			// 获取该文章的分类
			Map<String, String> map = new HashMap<String, String>();
			map.put("article_id", article_id);
			U_article article = this.u_articleService.findU_articleInfoByMap(map);
			mv = new ModelAndView("forward:/backstage/u_document_add.jsp");
			mv.addObject("article", article);
			// 帮助文档目录
			List<U_cate> aCates = u_cateService.findU_catesOrderByParentId(33);
			mv.addObject("document_cates", aCates);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/**
	 * 编辑 查看时显示内容
	 **/
	@RequestMapping({ "article-show" })
	public ModelAndView article_show(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = null;

		String article_id = request.getParameter("article_id");
		try {
			// 获取该文章的分类
			Map<String, String> map = new HashMap<String, String>();
			map.put("article_id", article_id);
			U_article article = this.u_articleService.findU_articleInfoByMap(map);
			if (article.getArticle_type() == 2) {
				mv = new ModelAndView("forward:/backstage/u_article_add2.jsp");
			} else if (article.getArticle_type() == 3) {
				mv = new ModelAndView("forward:/backstage/u_article_add3.jsp");
			} else {
				mv = new ModelAndView("forward:/backstage/u_article_add.jsp");
			}

			if (article.getArticle_type() == 2 || article.getArticle_type() == 3) {
				List<U_article_resource> article_resource = u_article_resourceService
						.getArticleResourcesByArticleID(article_id);
				article.setArticle_resources(article_resource);
			}
			mv.addObject("article", article);

			// 文章分类
			List<U_cate> article_cates = startOnLoadService.article_cates();
			mv.addObject("article_cates", article_cates);
			// 文章标签
			List<U_label> article_labs = u_labelService.getAlllabels(0);
			mv.addObject("article_labs", article_labs);
			// 获取所有自媒体
			Map paramMap = new HashMap();
			paramMap.put("status", 1);
			List<ApiT_member_wemedia> list = apiT_member_wemediaService.findT_member_wemediasByMap(paramMap);
			mv.addObject("wemedialist", list);

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/**
	 * 后台管理文章列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "webarticlelist" })
	public ModelAndView webarticlelist(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String cate_id = request.getParameter("cate_id");
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_list.jsp");

		try {
			List<U_article> list = null;
			String title = request.getParameter("title");
			if (cate_id == null) {
				list = this.u_articleService.findU_articlesOrderBy(1, title);
			} else {
				list = u_articleService.findU_articlesByCateId(cate_id);
			}

			// for (int i = 0; i < list.size(); i++) {
			// U_article cur_art = (U_article) list.get(i);
			// String content = cur_art.getContent();
			// if (content.length() > 14) {
			// cur_art.setContent(content.substring(0, 11) + "...");
			// }
			// String title = ((U_article) list.get(i)).getTitle();
			// if (title.length() > 10) {
			// cur_art.setTitle(title.substring(0, 8) + "...");
			// }
			// // 所属分类名称
			// String cates_Html = "";
			// List<U_article_cate> selected_art_cates = u_article_cateService
			// .findU_article_catesByArticle_id(cur_art.getId().toString());
			// List<U_cate> selected_cates = new ArrayList<U_cate>();
			// for (U_article_cate art_cate : selected_art_cates) {
			// U_cate cur_cate =
			// U_cateService.findU_cateById(art_cate.getCate_id());
			// selected_cates.add(cur_cate);
			// }
			// for (U_cate cate : selected_cates) {
			// if (cate != null) {
			// String cate_str = startOnLoadService.cates_str_OrderById(cate);
			// cate.setCate_full_name(cate_str);
			// cates_Html += cate_str + "<br/>";
			// }
			// }
			// cur_art.setCates_Html(cates_Html);
			//
			// }
			mv.addObject("msg", "0");
			mv.addObject("u_articles", list);
			mv.addObject("cate_id", cate_id);
			// List<ApiT_user_admin> users =
			// apiT_user_adminService.findT_user_admins();
			// mv.addObject("users", users);
			return mv;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/**
	 * 后台管理文章列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "document_articlelist" })
	public ModelAndView document_articlelist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String cate_id = request.getParameter("cate_id");
		ModelAndView mv = new ModelAndView("forward:/backstage/u_document_list.jsp");

		try {
			List<U_article> list = null;
			if (cate_id == null) {
				list = this.u_articleService.findU_articlesOrderBy(33, "");
			} else {
				list = u_articleService.findU_articlesByCateId(cate_id);
			}

			// for (int i = 0; i < list.size(); i++) {
			// U_article cur_art = (U_article) list.get(i);
			// String content = cur_art.getContent();
			// if (content.length() > 14) {
			// cur_art.setContent(content.substring(0, 11) + "...");
			// }
			// String title = ((U_article) list.get(i)).getTitle();
			// if (title.length() > 10) {
			// cur_art.setTitle(title.substring(0, 8) + "...");
			// }
			// // 所属分类名称
			// String cates_Html = "";
			// List<U_article_cate> selected_art_cates = u_article_cateService
			// .findU_article_catesByArticle_id(cur_art.getId().toString());
			// List<U_cate> selected_cates = new ArrayList<U_cate>();
			// for (U_article_cate art_cate : selected_art_cates) {
			// U_cate cur_cate =
			// U_cateService.findU_cateById(art_cate.getCate_id());
			// selected_cates.add(cur_cate);
			// }
			// for (U_cate cate : selected_cates) {
			// if (cate != null) {
			// String cate_str = startOnLoadService.cates_str_OrderById(cate);
			// cate.setCate_full_name(cate_str);
			// cates_Html += cate_str + "<br/>";
			// }
			// }
			// cur_art.setCates_Html(cates_Html);
			// }
			mv.addObject("msg", "0");
			mv.addObject("u_articles", list);
			mv.addObject("cate_id", cate_id);
			// List<ApiT_user_admin> users =
			// apiT_user_adminService.findT_user_admins();
			// mv.addObject("users", users);
			return mv;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/**
	 * 添加帮助文档
	 */
	@RequestMapping({ "documentaddpre" })
	public ModelAndView document_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_document_add.jsp");
		try {
			// 帮助文档目录
			List<U_cate> aCates = u_cateService.findU_catesOrderByParentId(33);
			mv.addObject("document_cates", aCates);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/**
	 * 添加文章前
	 */
	@RequestMapping({ "articleaddpre" })
	public ModelAndView article_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_add.jsp");
		try {
			// 文章分类
			List<U_cate> article_cates = startOnLoadService.article_cates();
			mv.addObject("article_cates", article_cates);
			// 文章标签
			List<U_label> article_labs = u_labelService.getAlllabels(0);
			mv.addObject("article_labs", article_labs);
			// 获取所有自媒体
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("status", 1);
			List<ApiT_member_wemedia> list = apiT_member_wemediaService.findT_member_wemediasByMap(paramMap);
			mv.addObject("wemedialist", list);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/**
	 * 添加图说文章前
	 */
	@RequestMapping({ "articleaddpre2" })
	public ModelAndView article_add_pre2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_add2.jsp");
		try {
			// 文章分类
			List<U_cate> article_cates = startOnLoadService.article_cates();
			mv.addObject("article_cates", article_cates);
			// 文章标签
			List<U_label> article_labs = u_labelService.getAlllabels(0);
			mv.addObject("article_labs", article_labs);
			// 获取所有自媒体
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("status", 1);
			List<ApiT_member_wemedia> list = apiT_member_wemediaService.findT_member_wemediasByMap(paramMap);
			mv.addObject("wemedialist", list);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/**
	 * 添加视频文章前
	 */
	@RequestMapping({ "articleaddpre3" })
	public ModelAndView article_add_pre3(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_add3.jsp");
		try {
			// 文章分类
			List<U_cate> article_cates = startOnLoadService.article_cates();
			mv.addObject("article_cates", article_cates);
			// 文章标签
			List<U_label> article_labs = u_labelService.getAlllabels(0);
			mv.addObject("article_labs", article_labs);
			// 获取所有自媒体
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("status", 1);
			List<ApiT_member_wemedia> list = apiT_member_wemediaService.findT_member_wemediasByMap(paramMap);
			mv.addObject("wemedialist", list);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/*
	 * 添加帮助文档
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping({ "document_addorUpdate" })
	public void document_addorUpdate(HttpServletRequest request, HttpServletResponse response, U_article article)
			throws Exception {
		try {
			if (article.getArticle_type() == null || "".equals(article.getArticle_type())) {// 添加文章
				if ((article.getImg2() == null || "".equals(article.getImg2()))
						&& (article.getImg3() == null || "".equals(article.getImg3()))) {
					article.setArticle_type(0);
				} else {
					article.setArticle_type(1);
				}
			}
			// 如果是图说则第一张图片为img1的地址，如果是视频则视频地址为img1的地址
			if (article.getArticle_type() == 2 || article.getArticle_type() == 3) {
				String[] resource_urls = request.getParameterValues("resource_url");
				article.setImg1(resource_urls[0]);
			}

			// 如果为图说 图说的第一张图片为img1的地址
			if (article.getArticle_type() == 3) {
				String[] resource_urls = request.getParameterValues("resource_url");
				article.setImg1(resource_urls[0]);
			}

			if (article.getId() == null || article.getId() == 0) {// 添加
				article.setAdd_time(HourGap.getNowTime());
				article.setModified_time(HourGap.getNowTime());
				article.setIs_visiable(Integer.valueOf(1));
				article.setStatus(1);
				u_articleService.insertU_articleReturnId(article);
			} else {// 修改
				u_articleService.updateU_article(article);
			}

			// 删除原来关联关系
			u_article_cateService.deleteArticleCates(article.getId());

			U_article_cate u_article_cate = new U_article_cate();
			u_article_cate.setAdd_time(DateUtil.nowTimeToString());
			u_article_cate.setArticle_id(article.getId());
			u_article_cate.setCate_id(Integer.valueOf(article.getCate_id()));
			u_article_cateService.insertU_article_cate(u_article_cate);

			// 如果是图说或者视频，文章资源入库
			if (article.getArticle_type() == 2 || article.getArticle_type() == 3) {
				// 删除原来资源
				u_article_resourceService.delarticle_resource(article.getId() + "");
				Integer resource_sort = 1;
				String[] resource_urls = request.getParameterValues("resource_url");
				String[] resource_descriptions = request.getParameterValues("resource_description");

				for (int i = 0; i < resource_urls.length; i++) {
					U_article_resource article_resource = new U_article_resource();
					article_resource.setDescription(resource_descriptions[i]);
					article_resource.setImg(resource_urls[i]);
					article_resource.setArticle_id(article.getId());
					article_resource.setSort(resource_sort);
					u_article_resourceService.insertU_article_resource(article_resource);
					resource_sort++;
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		ReturnSingleObject obj = new ReturnSingleObject("操作成功", "0000", null);
		JsonUtil.printJson(response, JsonUtil.object2json(obj));
	}

	/*
	 * 新增文章
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping({ "article_addorUpdate" })
	public void article_addorUpdate(HttpServletRequest request, HttpServletResponse response, U_article article)
			throws Exception {
		// ApiT_user_admin admin = (ApiT_user_admin)
		// request.getSession().getAttribute("user_admin");

		try {
			String[] label = request.getParameterValues("label");
			if (article.getArticle_type() == null || "".equals(article.getArticle_type())) {// 添加文章
				if ((article.getImg2() == null || "".equals(article.getImg2()))
						&& (article.getImg3() == null || "".equals(article.getImg3()))) {
					article.setArticle_type(0);
				} else {
					article.setArticle_type(1);
				}
			}
			// 如果是图说则第一张图片为img1的地址，如果是视频则视频地址为img1的地址
			if (article.getArticle_type() == 2 || article.getArticle_type() == 3) {
				String[] resource_urls = request.getParameterValues("resource_url");
				article.setImg1(resource_urls[0]);
			}

			// 如果为图说 图说的第一张图片为img1的地址
			if (article.getArticle_type() == 3) {
				String[] resource_urls = request.getParameterValues("resource_url");
				article.setImg1(resource_urls[0]);
			}

			String sl = "";
			if (label != null && label.length > 0) {
				for (int i = 0; i < label.length; i++) {
					sl = sl + label[i] + ":";
				}
				sl = sl.substring(0, sl.length() - 1);
			}
			article.setLabel(sl);
			article.setKeywords(sl);

			if (article.getId() == null || article.getId() == 0) {// 添加
				String wemediaid = request.getParameter("wemediaid");
				ApiT_member_wemedia apiT_member_wemedia = apiT_member_wemediaService
						.findT_member_wemediaById(Integer.valueOf(wemediaid));
				article.setCreater_id(apiT_member_wemedia.getUser_id() + "");
				article.setOrg_id(wemediaid);
				article.setAdd_time(HourGap.getNowTime());
				article.setModified_time(HourGap.getNowTime());
				article.setIs_visiable(Integer.valueOf(1));
				article.setStatus(1);
				// 自媒体的城市信息
				String city = apiT_member_wemedia.getAddress().split(":")[0].split("%")[1];
				article.setCity(city);
				u_articleService.insertU_articleReturnId(article);
			} else {// 修改
				String wemediaid = request.getParameter("wemediaid");
				ApiT_member_wemedia apiT_member_wemedia = apiT_member_wemediaService
						.findT_member_wemediaById(Integer.valueOf(wemediaid));
				article.setCreater_id(apiT_member_wemedia.getUser_id() + "");
				article.setOrg_id(wemediaid);
				String city = apiT_member_wemedia.getAddress().split(":")[0].split("%")[1];
				article.setCity(city);
				u_articleService.updateU_article(article);
			}

			// 删除原来关联关系
			u_article_cateService.deleteArticleCates(article.getId());

			U_article_cate u_article_cate = new U_article_cate();
			u_article_cate.setAdd_time(DateUtil.nowTimeToString());
			u_article_cate.setArticle_id(article.getId());
			u_article_cate.setCate_id(Integer.valueOf(article.getCate_id()));
			u_article_cateService.insertU_article_cate(u_article_cate);

			// 如果是图说或者视频，文章资源入库
			if (article.getArticle_type() == 2 || article.getArticle_type() == 3) {
				// 删除原来资源
				u_article_resourceService.delarticle_resource(article.getId() + "");
				Integer resource_sort = 1;
				String[] resource_urls = request.getParameterValues("resource_url");
				String[] resource_descriptions = request.getParameterValues("resource_description");

				for (int i = 0; i < resource_urls.length; i++) {
					U_article_resource article_resource = new U_article_resource();
					article_resource.setDescription(resource_descriptions[i]);
					article_resource.setImg(resource_urls[i]);
					article_resource.setArticle_id(article.getId());
					article_resource.setSort(resource_sort);
					u_article_resourceService.insertU_article_resource(article_resource);
					resource_sort++;
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		ReturnSingleObject obj = new ReturnSingleObject("操作成功", "0000", null);
		JsonUtil.printJson(response, JsonUtil.object2json(obj));
	}

	// 添加分类
	@RequestMapping({ "cateList" })
	public ModelAndView cateList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_cat_list");
		try {

			List<U_cate> datas = U_cateService.findU_cates();
			mv.addObject("datas", datas);
			mv.addObject("msg", "0");

			return mv;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	// 添加标签
	@RequestMapping({ "initAddLabel" })
	public ModelAndView initAddLabel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_label_add");
		try {
			List<Ylj_All_Label_Obj> labs = this.u_labelService.findAllU_labels();
			String s3 = JsonUtil.object2json(labs);
			mv.addObject("labels", s3);
			mv.addObject("msg", "0");

			return mv;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	// 添加标签
	@RequestMapping({ "addLabel" })
	public ModelAndView addLabel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_label_add");
		String level1 = request.getParameter("level1");
		String cate_name = request.getParameter("label_name");
		String sort = request.getParameter("sort");
		try {

			boolean flag = u_articleService.addLabel(level1, cate_name, sort);
			if (flag) {

				mv.addObject("msg", "0");
			} else {
				mv.addObject("msg", "1");
			}

			List<Ylj_All_Label_Obj> labs = this.u_labelService.findAllU_labels();
			String s3 = JsonUtil.object2json(labs);
			mv.addObject("labels", s3);

			return mv;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	@RequestMapping({ "show_cate" })
	public ModelAndView show_cate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_cate_modify");

		String cate_id = request.getParameter("cate_id");
		try {
			U_cate cate = U_cateService.findU_cateById(Integer.parseInt(cate_id));

			mv.addObject("cate", cate);
			mv.addObject("msg", "0");
			return mv;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	@RequestMapping({ "modifyCate" })
	public ModelAndView modifyCate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_cate_modify");

		String cate_id = request.getParameter("cate_id");
		String cate_name = request.getParameter("cate_name");
		String cate_desc = request.getParameter("cate_desc");
		String sort = request.getParameter("sort");
		try {

			U_cate cate = U_cateService.findU_cateById(Integer.parseInt(cate_id));

			cate.setCate_desc(cate_desc);
			cate.setCate_name(cate_name);
			cate.setSort(Integer.parseInt(sort));
			U_cateService.updateU_cate(cate);

			mv.addObject("cate", cate);
			mv.addObject("msg", "0");
			return mv;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "1");
		}
		return mv;
	}

	/***
	 * 修改文章
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/editor" })
	public ModelAndView editor(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_article_editor");

		String article_id = request.getParameter("article_id");
		String header_img = request.getParameter("header_img");
		String img1 = request.getParameter("img1");
		// String level1 = request.getParameter("level1");
		String description = request.getParameter("description");
		String content = request.getParameter("content");
		String title = request.getParameter("title");
		String[] cate_ids = request.getParameterValues("first_cate_id");
		String[] label = request.getParameterValues("label");
		String apl_up = request.getParameter("apl_up");
		String apl_down = request.getParameter("apl_down");

		try {
			String now = HourGap.getNowTime();

			U_article article = this.u_articleService.findU_articleById(Integer.valueOf(article_id));
			article.setAdd_time(now);
			String article_type = "";
			article_type = "-1";

			article.setArticle_type(Integer.valueOf(article_type));

			article.setCate_id(cate_ids[0]);
			article.setContent(content);
			article.setDescription(description);
			article.setHeader_img(header_img);
			article.setModified_time(HourGap.getNowTime());
			ApiT_user_admin admin = (ApiT_user_admin) request.getSession().getAttribute("user_admin");
			// article.setModified_by(admin.getUser_id());
			article.setImg1(img1);

			article.setApl_down(Integer.valueOf(apl_down));
			article.setApl_up(Integer.valueOf(apl_up));

			String sl = "";
			for (int i = 0; i < label.length; i++) {
				sl = sl + label[i] + ";";
			}
			sl = sl.substring(0, sl.length() - 1);

			article.setLabel(sl);
			article.setTitle(title);

			int ret = this.u_articleService.updateU_article(article);
			// 删除原有关系
			u_article_cateService.deleteArticleCates(Integer.valueOf(article_id));
			// 插入文章分类关联表
			// for (int i = 0; i < cate_ids.length; i++) {
			// u_articleService.insertArticle_cate(article_id, cate_ids[i]);
			// }
			//
			if (ret == 0) {
				mv.addObject("msg", "10");
			} else {
				mv.addObject("msg", "8");
			}
			mv.addObject("article", article);

			List<Ylj_Article_Label_Obj> datas = new ArrayList<Ylj_Article_Label_Obj>();

			datas = this.u_articleService.findAllLabel();
			String s = JsonUtil.object2json(datas);
			mv.addObject("datas", s);

			List<Ylj_All_Label_Obj> labs = this.u_labelService.findAllU_labels();
			String s3 = JsonUtil.object2json(labs);
			mv.addObject("labels", s3);

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			mv.addObject("msg", "10");
		}
		//
		return mv;
	}

	/**
	 * 返回子标签集合
	 * 
	 * @return
	 */
	@RequestMapping(value = "/labels_find_by_parent_id")
	public void labels_find_by_parent_id(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//
		List<U_label> u_labels = null;
		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			u_labels = u_labelService.findU_labelsByParent_id(id);

		}
		//
		ReturnListObject<U_label> ret_obj = new ReturnListObject<U_label>(Util.RESULT_RC_SUCCESS, "获取成功", u_labels);
		JsonUtil.printJson(response, JsonUtil.object2json(ret_obj));
	}

	@RequestMapping({ "del" })
	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String article_id = request.getParameter("article_id");

			U_article article = this.u_articleService.findU_articleById(Integer.valueOf(Integer.parseInt(article_id)));

			article.setIs_visiable(Integer.valueOf(0));

			this.u_articleService.updateU_article(article);

			ReturnSingleObject obj = new ReturnSingleObject("操作成功", "0000", null);
			JsonUtil.printJson(response, JsonUtil.object2json(obj));
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();

			ReturnSingleObject obj = new ReturnSingleObject("系统异常", "0001", null);
			JsonUtil.printJson(response, JsonUtil.object2json(obj));
		}
	}

	@RequestMapping({ "articledelete" })
	public void articledelete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		BaseObj baseObj = new BaseObj();
		try {
			String article_id = request.getParameter("id");
			u_articleService.deleteU_article(Integer.valueOf(article_id));
			baseObj.handleSuccess();
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			baseObj.handleException(e);
			JsonUtil.printJson(response, JsonUtil.object2json(baseObj));
		}
	}

	@RequestMapping({ "articleshow" })
	public void articleshow(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String article_id = request.getParameter("article_id");

			U_article article = this.u_articleService.findU_articleById(Integer.valueOf(Integer.parseInt(article_id)));

			if (article.getIs_visiable().intValue() == 0)
				article.setIs_visiable(Integer.valueOf(1));
			else
				article.setIs_visiable(0);

			this.u_articleService.updateU_article(article);

			ReturnSingleObject obj = new ReturnSingleObject("操作成功", "0000", null);
			JsonUtil.printJson(response, JsonUtil.object2json(obj));
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			ReturnSingleObject obj = new ReturnSingleObject("系统异常", "0001", null);
			JsonUtil.printJson(response, JsonUtil.object2json(obj));
		}
	}

	/**
	 * 上传缩略图
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "pic-upload")
	public void pic_upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ModelMap model
		String path = ImageUtils.getServletWebAppsPath(request) + "/";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String sdfStr = sdf.format(new Date());
		String fileName = sdfStr + "_" + file.getOriginalFilename();

		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		String smallpic_path = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 保存
		try {
			file.transferTo(targetFile);
			smallpic_path = ImageUtils.getDataBaseImagePath() + "/" + fileName;

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "上传成功！");
			map.put("datas", smallpic_path);

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		//
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}
}
